﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using HtmlAgilityPack;
using LoU.Client.Service;

namespace Lou.Client.Service.Authentication
{
    public static class Game
    {
        public static Dictionary<string, World> Getworlds(string mail, string password)
        {
            CookieContainer jar = new CookieContainer();
            jar.Add(new Cookie(Constants.IS_RETURNING_COOKIE_NAME, Constants.IS_RETURNING_COOKIE_VALUE, Constants.IS_RETURNING_COOKIE_PATH, Constants.DOMAIN));
            string page = Post(@"https://www.lordofultima.com/en/user/login", jar, new Dictionary<string, string>
            {
                { Constants.MAIL_PARAM_NAME, mail },
                { Constants.PASSWORD_PARAM_NAME, password },
            });
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(page);

            Dictionary<string, World> worlds = new Dictionary<string, World>();
            doc.DocumentNode.SelectNodes("//form").Where(a => a.Attributes["action"].Value.Contains("prodgame")).Select(n =>
                new World
                {
                    Url = n.Attributes["action"].Value,
                    WorldId = new Guid(n.NextSibling.NextSibling.Attributes["value"].Value),
                    Label = n.NextSibling.NextSibling.NextSibling.NextSibling.FirstChild.NextSibling.Attributes["value"].Value,
                }).ToList().ForEach(a => worlds.Add(a.Label, a));
            return worlds;
        }

        private static string Get(string url, CookieContainer jar)
        {
            return Request(url, "GET", jar);
        }

        private static string Post(string url, CookieContainer jar, Dictionary<string, string> postData)
        {
            return Request(url, "POST", jar, postData);
        }

        private static string Request(string url, string method, CookieContainer jar, Dictionary<string, string> data = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = method;
            request.CookieContainer = jar;
            if (data != null)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] postData = Encoding.UTF8.GetBytes(string.Join("&", data.Select(a => HttpUtility.UrlEncode(a.Key) + "=" + HttpUtility.UrlEncode(a.Value))));
                request.ContentLength = postData.Length;
                request.GetRequestStream().Write(postData, 0, postData.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }
}
